<template>
  <div class="pageContent">
    <div class="centerAll">
      <Table ref="xrTable" :list-api="list" :status-api="status" :table-column="tableColumn" :page-config="pageConfig"
        :table-config="tableConfig" @openViewForm="openViewForm" @openEditForm="openEditForm">
        <template v-slot:addBtn>
          <el-button type="success" @click="openCreateForm()">新增</el-button>
        </template>
      </Table>
    </div>
  </div>

  <el-dialog v-model="dialogFormVisible" :title="isRead ? '查看' : '新增'" width="860px">
    <el-form :model="form" :rules="rules" ref="ruleFormRef" label-position="right" label-width="auto">
      <el-form-item label="加工方式名称：" prop="name">
        <span v-if="isRead">{{form.name}}</span>
        <el-input v-else v-model="form.name" autocomplete="off" maxlength="50" show-word-limit
          placeholder="请输入加工方式名称" />
      </el-form-item>
      <el-form-item label="对外展示名称：" prop="show_name">
        <span v-if="isRead">{{form.show_name}}</span>
        <el-input v-else v-model="form.show_name" autocomplete="off" maxlength="50" show-word-limit
          placeholder="请输入对外展示名称" />
      </el-form-item>
      <el-form-item label="关联药品类型：" prop="type_id">
        <span v-if="isRead">{{form.type_id}}</span>
        <el-select v-else v-model="form.type_id" clearable placeholder="请选择关联药品类型">
          <el-option v-for="(o, ok) in drugTypeOptions" :key="ok" :label="o.name" :value="o.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="排序优先级：" prop="sort">
        <span v-if="isRead">{{form.sort}}</span>
        <div class="priority" v-else>
          <el-input-number v-model="form.sort" :min="0" :max="10" controls-position="right" class="mx-4"
            placeholder="请输入排序优先级" />
        </div>
      </el-form-item>
      <el-form-item label="用法用量模板：" prop="use_limit_id" required>
        <span v-if="isRead">{{form.use_limit_id}}</span>
        <el-select v-else v-model="form.use_limit_id" clearable placeholder="请选择用法用量模板" @change="useLimitChange">
          <el-option v-for="(o, ok) in useLimitTemplateOptions" :key="ok" :label="o.value" :value="o.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="用法用量默认值：" prop="usage">
        <span v-if="isRead">{{form.usage}}</span>
        <div v-else class="usage">
          <span v-for="(u, uk) in useLimitArr" :key="uk">{{ u }}
            <el-input-number v-if="uk !== useLimitArr.length-1" v-model="form.use_limit[uk]" :controls="false"
              controls-position="right" class="mx-4" />
          </span>
        </div>
      </el-form-item>
      <el-form-item label="预计出药率" required prop="rate">
        <span v-if="isRead">{{form.rate_min}}% - {{form.rate_max}}%</span>
        <div v-else class="flex">
<!--          <el-form-item prop="rate_min" style="width: 80px">-->
            <el-input-number v-model="form.rate_min" :controls="false" controls-position="right" class="mx-4 w-80"
              placeholder="请输入" />%
<!--          </el-form-item>-->
          <span style="margin-right: 20px; margin-left: 20px">-</span>
          <span v-if="isRead">{{form.rate_min}}</span>
<!--          <el-form-item prop="rate_max" style="width: 80px">-->
            <el-input-number v-model="form.rate_max" :controls="false" controls-position="right" class="mx-4 w-80"
              placeholder="请输入" />%
<!--          </el-form-item>%-->
        </div>
      </el-form-item>

      <el-form-item label="是否有包装：" prop="had_pack">
        <span v-if="isRead">{{form.had_pack == 1?'是':'否'}}</span>
        <el-radio-group v-model="form.had_pack" class="ml-4" v-else>
          <el-radio :value="1" size="large">是</el-radio>
          <el-radio :value="2" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否有制法：" prop="had_production">
        <span v-if="isRead">{{form.had_production == 1?'是':'否'}}</span>
        <el-radio-group v-model="form.had_production" class="ml-4" v-else>
          <el-radio :value="1" size="large">是</el-radio>
          <el-radio :value="2" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否有制粉颗粒度：" prop="had_milling">
        <span v-if="isRead">{{form.had_milling == 1?'是':'否'}}</span>
        <el-radio-group v-model="form.had_milling" class="ml-4" v-else>
          <el-radio :value="1" size="large">是</el-radio>
          <el-radio :value="2" size="large">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注：">
        <span v-if="isRead">{{form.remark}}</span>
        <el-input v-else v-model="form.remark" autocomplete="off" maxlength="500" show-word-limit type="textarea"
          placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template v-if="!isRead" #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm()">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
  // import { rateMaxValidator } from "@/utils/common"
  import {
    ref,
    reactive,
    onMounted,
    nextTick,
    watch
  } from 'vue'
  import {
    list,
    status,
    useLimit,
    create,
    update
  } from "@/api/drug/drugProcess";
  import {
    search as drugTypeSearch
  } from "@/api/drug/drugType"
  import {
    pageConfig,
    tableColumn,
    tableConfig
  } from "./config";
  import Table from "@/components/Table/index.vue";

  const useLimitArr = ref([])
  const useLimitTemplateOptions = ref([])
  const drugTypeOptions = ref([])
  const isRead = ref(false)
  const xrTable = ref()
  const form = ref({
    use_limit_id: 1,
    use_limit: [],
    had_production: 2,
    had_milling: 2,
    had_pack: 2
  })
  const ruleFormRef = ref()
  const dialogFormVisible = ref(false)
  const rateMaxValidator = (rule, value, callback) => {
    ruleFormRef.value.validateField("rate");
    callback()
  }
  const rateValidator = (rule, value, callback) => {
    if (!value || value === "") {
      callback(new Error("请填写预计出药率"))
    } else if (form.value.rate_min === "" || form.value.rate_max === "") {
      callback(new Error("请填写预计出药率"))
    } else if (form.value.rate_max <= form.value.rate_min) {
      callback(new Error("最大值必须大于最小值"))
    } else {
      callback()
    }
  }
  const rules = reactive({
    name: [{
      required: true,
      message: '请填写加工方式名称',
      trigger: 'blur'
    }],
    show_name: [{
      required: true,
      message: '请填写对外展示名称',
      trigger: 'blur'
    }],
    sort: [{
      required: true,
      message: '请填写对外展示名称',
      trigger: 'blur'
    }],
    type_id: [{
      required: true,
      message: '请选择关联药品类型',
      trigger: 'blur'
    }],
    rate: [{
      validator: rateValidator,
    }],
    rate_min: [{
      validator: rateMaxValidator,
      trigger: 'blur',
    }],
    rate_max: [{
      validator: rateMaxValidator,
      trigger: 'blur',
    }],
    had_pack: [{
      required: true,
      trigger: 'blur'
    }],
    had_production: [{
      required: true,
      trigger: 'blur'
    }],
    had_milling: [{
      required: true,
      trigger: 'blur'
    }],
  });

  const openCreateForm = () => {
    isRead.value = false
    dialogFormVisible.value = true

    nextTick(() => {
      form.value = {
        use_limit_id: 1,
        use_limit: [],
        had_production: 2,
        had_milling: 2,
        had_pack: 2
      };
      ruleFormRef.value.resetFields()
      ruleFormRef.value.clearValidate()
    })
  }

  const openViewForm = (row) => {
    isRead.value = true
    dialogFormVisible.value = true
    form.value = {
      ...row
    }
    if (row.use_limit) {
      form.value.use_limit = row.use_limit.split("_")
    }
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }
  const openEditForm = (row) => {
    isRead.value = false
    dialogFormVisible.value = true
    form.value = {
      ...row
    }
    if (row.use_limit) {
      form.value.use_limit = row.use_limit.split("_")
    }
    console.log(form.value)
    nextTick(() => {
      ruleFormRef.value.clearValidate()
    })
  }

  watch(() => form.value.rate_min, (newValue, oldValue) => {
    if (form.value.rate_min && form.value.rate_max) {
      form.value.rate = "xxx"
    } else {
      form.value.rate = ""
    }
  })
  watch(() => form.value.rate_max, (newValue, oldValue) => {
    if (form.value.rate_min && form.value.rate_max) {
      form.value.rate = "xxx"
    } else {
      form.value.rate = ""
    }
  })

  const useLimitChange = (value) => {
    form.value.use_limit = []
    const useLimit = useLimitTemplateOptions.value.find(item => item.id === value)
    useLimitArr.value = useLimit.value.split("X");
  }


  const getUseLimitTemplate = async () => {
    const res = await useLimit();
    useLimitTemplateOptions.value = res.data
  }

  const getDrugType = async () => {
    const res = await drugTypeSearch();
    drugTypeOptions.value = res.data
  }

  const submitForm = async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        const options = {
          ...form.value
        }
        if (options.use_limit) {
          options.use_limit = options.use_limit.join("_")
        }
        if (options.id) {
          await update(options)
        } else {
          await create(options)
        }
        dialogFormVisible.value = false
        xrTable.value.resetFormParent()
      } else {
        console.log('error submit!', fields)
      }
    })
  }

  onMounted(async () => {
    await getUseLimitTemplate()
    try {
      await getDrugType()
    } catch (e) {
      console.log(e)
    }
    useLimitChange(form.value.use_limit_id);
  })
</script>

<style lang="scss" scoped>
  .el-form-item {
    margin-right: 12px;
  }

  .custom-card {
    width: 100%;
  }

  .buttonAll {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
  }

  .usage ::v-deep .el-input-number {
    margin: 0 8px;
    width: 60px;
  }

  .priority ::v-deep .el-input__inner {
    text-align: left;
  }

  .rate ::v-deep .el-input-number {
    margin: 0 8px 0 0;
    width: 120px;
  }

  .priority {
    width: 100%;
  }

  .priority ::v-deep .el-input-number {
    width: 100%;
  }

  .el-card {
    box-shadow: none;
  }

  .table-container {
    overflow-x: auto;
  }

  .upload-demo {
    display: flex;

    >* {
      position: relative;
      flex: 1;
      padding: 5px 20px;
      margin: 10px;
      background-color: white;
    }
  }

  .demo-pagination-block {
    margin: 20px 0;
    display: flex;
    justify-content: center;
  }

  .demo-pagination-block+.demo-pagination-block {
    margin-top: 10px;
  }

  .demo-pagination-block .demonstration {
    margin-bottom: 16px;
  }
</style>